/**
 * 
 */
package com.ynet.middleground.riskmanage.model;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.host.HostConstants;
import com.ynet.middleground.riskmanage.bean.*;
import com.ynet.middleground.riskmanage.dao.DgInventoryRespMapper;
import com.ynet.middleground.riskmanage.dao.DgInventoryStaticMapper;
import com.ynet.middleground.riskmanage.dao.MasterGoodsTypeMapper;
import com.ynet.middleground.riskmanage.dto.*;
import com.ynet.middleground.riskmanage.dto.rizhaogang.RzgCustomsReleaseDTO;
import com.ynet.middleground.riskmanage.entity.*;
import com.ynet.middleground.riskmanage.external.MainBusinessConfig;
import com.ynet.middleground.riskmanage.external.MasterDataSystemConfig;
import com.ynet.middleground.riskmanage.external.port.PortUriEnum;
import com.ynet.middleground.riskmanage.external.qcc.ApiHelper;
import com.ynet.middleground.riskmanage.mq.producer.ZtProducer;
import com.ynet.middleground.riskmanage.utils.ApiUtil;
import com.ynet.middleground.riskmanage.utils.BeanUtil;

/**
 * @ClassName DaGangModel
 * @Description 大港服务处理逻辑
 * @Author songyf
 * @Date 2020/8/18 10:55
 * @Version 1.0
 */
@Component
public class DaGangModel extends ServiceImpl<MasterGoodsTypeMapper, MasterGoodsType> {

    @Autowired
    MasterGoodsTypeMapper masterGoodsTypeMapper;

    @Autowired
    ApiUtil apiUtil;

    @Autowired
    ApiHelper apiHelper;

    @Autowired
    MainBusinessConfig mainBusinessConfig;

    @Autowired
    MasterDataSystemConfig masterDataSystemConfig;

    @Autowired
    DgShipCycleModel dgShipCycleModel;

    @Autowired
    DgCustomsClearanceModel dgCustomsClearanceModel;

    @Autowired
    DgInventoryRespMapper dgInventoryRespMapper;

    @Autowired
    DgCargoInYardModel dgCargoInYardModel;

    @Autowired
    DgJCargoControlModel dgJCargoControlModel;

    @Autowired
    DgDCargoControlModel dgDCargoControlModel;

    @Autowired
    DgYardCargoModel dgYardCargoModel;

    @Autowired
    DgYardCargoJModel dgYardCargoJModel;

    @Autowired
    DgInventoryStaticMapper dgInventoryStaticMapper;

    @Autowired
    ZtProducer ztProducer;

    /**
     * 日志打印时显示的名称
     */
    public static final String LOG_NAME = "大港";

    public static final String ORG_ID = "1";

    /**
     * @author songyf
     * @Description 货种信息查询
     * @Date 2020-08-18 14:36
     * @Param MasterGoodsTypeQueryReqPager
     * @return MasterGoodsTypeDTO
     **/
    public List<MasterGoodsTypeDTO> getMasterGoodsType(MasterGoodsTypeQueryReqPager req) {
        LambdaQueryWrapper<MasterGoodsType> queryWrapper = new LambdaQueryWrapper<MasterGoodsType>();
        if (StringUtils.isNotBlank(req.getTypeCode())) {
            queryWrapper.eq(MasterGoodsType::getCode, req.getTypeCode());
        }
        PagerInfo pagerInfo = req.getPagerInfo();
        Page<MasterGoodsType> masterGoodsTypePage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        IPage<MasterGoodsType> page = masterGoodsTypeMapper.selectPage(masterGoodsTypePage, queryWrapper);
        List<MasterGoodsType> list = page.getRecords();
        List<MasterGoodsTypeDTO> masterGoodsTypeDTOList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            MasterGoodsType masterGoodsType = list.get(i);
            MasterGoodsTypeDTO masterGoodsTypeDTO = new MasterGoodsTypeDTO();
            masterGoodsTypeDTO.setId(masterGoodsType.getDetailId());
            masterGoodsTypeDTO.setName(masterGoodsType.getName());
            masterGoodsTypeDTO.setCode(masterGoodsType.getCode());
            masterGoodsTypeDTO.setLevel(masterGoodsType.getLevel());
            masterGoodsTypeDTO.setHighlevel(masterGoodsType.getHigherCode());
            masterGoodsTypeDTO.setStatus(masterGoodsType.getStatus());
            masterGoodsTypeDTOList.add(masterGoodsTypeDTO);
        }
        pagerInfo.setTotal(page.getTotal());
        return masterGoodsTypeDTOList;
    }

    /**
     * @author songyf
     * @Description 获取货种信息
     * @Date 2020-08-18 14:36
     **/
    @Transactional(rollbackFor = Exception.class)
    public void getMasterGoodsType() {
        Map<String, Object> params = new HashMap<>();
        params.put("userKey", masterDataSystemConfig.getKey());
        params.put("tableName", "dim_cargo_class");
        String url = masterDataSystemConfig.getApiHost() + masterDataSystemConfig.getUrlGoods();
        JSONObject apiResult = apiUtil.sendApi(null, params, url, HostConstants.HTTP_METHOD_POST, LOG_NAME);
        JSONArray jsonArray = apiResult.getJSONArray("dataList");
        Map<String, String> change = new HashMap<>();
        change.put("id", "detailId");
        change.put("jb", "level");
        change.put("isuse", "status");
        change.put("higher_code", "HIGHER_CODE");
        change.put("name", "NAME");
        change.put("short_name", "SHORT_NAME");
        change.put("remark", "REMARK");
        change.put("code", "CODE");
        jsonArray = BeanUtil.changeJsonArr(jsonArray, change);
        List<MasterGoodsType> masterGoodsTypeList = jsonArray.toJavaList(MasterGoodsType.class);
        for (int i = 0; i < masterGoodsTypeList.size(); i++) {
            masterGoodsTypeList.get(i).setGmtCreate(LocalDateTime.now());
        }
        LambdaQueryWrapper<MasterGoodsType> deleteMasterGoodsType = new LambdaQueryWrapper<MasterGoodsType>();
        IfpLogger.info("masetr_goods_type", "删除原有大港货种信息, api" + url);
        deleteMasterGoodsType.like(MasterGoodsType::getId, "");
        this.remove(deleteMasterGoodsType);
        IfpLogger.info("masetr_goods_type", "开始同步大港货种信息, api" + url);
        this.saveBatch(masterGoodsTypeList);
        ztProducer.sendMessagesDgGoodsTypeIn(jsonArray);
        return;
    }

    /**
     * @author songyf
     * @Description 船期信息查询
     * @Date 2020-08-19 14:36
     * @Param DgShipCycleQueryReq
     * @return DgShipCycleDTO
     **/
    @Transactional(rollbackFor = Exception.class)
    public List<DgShipCycleDTO> getShipCycle(DgShipCycleQueryReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", ORG_ID);
        params.put("shipnamech", req.getShipName());
        params.put("shipnameen", req.getEngShipName());
        params.put("invoyage", req.getVoyage());
        params.put("shipcycleid", req.getShipNo());
        params = apiHelper.reqParamsProc(params);
        String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.SHIP_CYCLE_URL.getUrl();
        JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.SHIP_CYCLE_URL.getCode(), url, null, params,
            HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
        JSONArray result = apiResult.getJSONArray("data");
        String code = apiResult.getString("result");
        String message = apiResult.getString("message");
        if ("0".equals(code)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        List<DgVoyageResp> dgVoyageRespList = result.toJavaList(DgVoyageResp.class);
        List<DgVoyageResp> dgVoyageRespLists = new ArrayList<>();
        for (int i = 0; i < dgVoyageRespList.size(); i++) {
            DgVoyageResp dgVoyageResp = dgVoyageRespList.get(i);
            dgVoyageResp.setChannel(req.getChannel());
            dgVoyageResp.setCreateBy(req.getOperationUserId());
            dgVoyageResp.setModifiedBy(req.getOperationUserId());
            dgVoyageResp.setGmtCreate(LocalDateTime.now());
            dgVoyageResp.setGmtModified(LocalDateTime.now());
            dgVoyageRespLists.add(dgVoyageResp);
        }
        dgShipCycleModel.saveBatch(dgVoyageRespLists);
        Map<String, String> change = new HashMap<>();
        change.put("shipnamech", "shipName");
        change.put("engshipname", "engShipName");
        change.put("inoutward", "inorOut");
        change.put("invoyage", "invoyage");
        change.put("arrivedate", "anDate");
        change.put("expectarrivedate", "expectDate");
        change.put("incargoname", "inName");
        change.put("inloadqty", "inWeight");
        result = BeanUtil.changeJsonArr(result, change);
        List<DgShipCycleDTO> dgShipCycleDTO = result.toJavaList(DgShipCycleDTO.class);;
        return dgShipCycleDTO;
    }

    /**
     * @author songyf
     * @Description 海关放行信息查询
     * @Date 2020-08-19 17:36
     * @Param DgShipCycleQueryReq
     * @return DgShipCycleDTO
     **/
    @Transactional(rollbackFor = Exception.class)
    // public List<DgCustomsReleaseDTO> getCustomsRelease(DgCustomsReleaseReq req) {
    public List<RzgCustomsReleaseDTO> getCustomsRelease(DgCustomsReleaseReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", ORG_ID);
        params.put("entry_id", req.getCustomsNo());
        params = apiHelper.reqParamsProc(params);
        String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.CUSTOMS_RELEASE_URL.getUrl();
        JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.CUSTOMS_RELEASE_URL.getCode(), url, null, params,
            HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
        JSONArray result = apiResult.getJSONArray("data");
        String code = apiResult.getString("result");
        String message = apiResult.getString("message");
        if ("0".equals(code)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        List<DgCustomsClearance> dgCustomsClearanceList = result.toJavaList(DgCustomsClearance.class);
        List<DgCustomsClearance> dgCustomsClearanceLists = new ArrayList<>();
        for (int i = 0; i < dgCustomsClearanceList.size(); i++) {
            DgCustomsClearance dgCustomsClearance = dgCustomsClearanceList.get(i);
            dgCustomsClearance.setChannel(req.getChannel());
            dgCustomsClearance.setCreateBy(req.getOperationUserId());
            dgCustomsClearance.setModifiedBy(req.getOperationUserId());
            dgCustomsClearance.setGmtCreate(LocalDateTime.now());
            dgCustomsClearance.setGmtModified(LocalDateTime.now());
            dgCustomsClearanceLists.add(dgCustomsClearance);
        }
        dgCustomsClearanceModel.saveBatch(dgCustomsClearanceLists);
        Map<String, String> change = new HashMap<>();
        change.put("bill_no", "billNo");
        change.put("entry_id", "customsNo");
        change.put("pass_pack_no", "inNumber");
        change.put("unit_v", "unitNum");
        change.put("pack_no", "inNum");
        change.put("net_wt", "weight");
        change.put("gros_wt", "toWeight");
        change.put("r_date", "toDate");
        change.put("warehouse_code", "customsState");
        result = BeanUtil.changeJsonArr(result, change);
        // List<DgCustomsReleaseDTO> dgCustomsReleaseDTO = result.toJavaList(DgCustomsReleaseDTO.class);
        List<RzgCustomsReleaseDTO> returnResult = result.toJavaList(RzgCustomsReleaseDTO.class);
        return returnResult;
    }

    /**
     * @author songyf
     * @Description 港存信息查询
     * @Date 2020-08-19 20:36
     * @Param DgYardCargoQueryReq
     * @return DgYardCargoDTO
     **/
    @Transactional(rollbackFor = Exception.class)
    public DgYardCargoDTO getYardCargoDTO(DgYardCargoQueryReq req) {
        // Add By liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        if (!StringUtils.isEmpty(req.getSortField()) && StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序方式", "DAGM0001");
        }
        if (StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
            throw new BusinessException("请上送排序字段", "DAGM0002");
        }
        if (!StringUtils.isEmpty(req.getSortOrder())) {
            List<String> sortOrders = mainBusinessConfig.getSortOrder();
            if (!sortOrders.contains(req.getSortOrder())) {
                throw new BusinessException("请上送有效排序方式", "DAGM0005");
            }
        }
        if (!StringUtils.isEmpty(req.getSortField())) {
            List<String> dagangSortField = mainBusinessConfig.getDagangSortField();
            if (dagangSortField.size() == 0) {
                throw new BusinessException("请联系管理员维护大港有效排序字段", "DAGM0004");
            }
            if (dagangSortField.size() > 0) {
                if (!dagangSortField.contains(req.getSortField())) {
                    throw new BusinessException("请上送有效排序字段", "DAGM0003");
                }
            }
        }
        // Add By liwq On 2021-01-27 End

        DgYardCargoDTO dgYardCargoDTO = new DgYardCargoDTO();
        Map<String, Object> params = new HashMap<>();
        params.put("id", ORG_ID);
        params.put("workentrustid", req.getUserNo());
        params.put("workentrustname", req.getUserName());
        params.put("cargonamecode", req.getTypeCode());
        params.put("cargoname", req.getTypeName());
        params.put("querytype", "0");
        params.put("informationtype", req.getInformationType());

        // Add By Liwq On 2021-01-27 Start
        // 增加排序功能&指定字段排序功能
        // 只有静态允许排序
        if ("1".equals(req.getInformationType())) {
            if (!StringUtils.isEmpty(req.getSortField()) && !StringUtils.isEmpty(req.getSortOrder())) {
                params.put("sortfield", req.getSortField());
                params.put("sortorder", req.getSortOrder());
            }
        }

        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageNum()))) {
            params.put("pagenum", req.getPagerInfo().getPageNum());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getPageSize()))) {
            params.put("pagesize", req.getPagerInfo().getPageSize());
        }
        if (!StringUtils.isEmpty(String.valueOf(req.getPagerInfo().getTotal()))) {
            params.put("total", req.getPagerInfo().getTotal());
        }
        // Add By Liwq On 2021-01-27 End

        params = apiHelper.reqParamsProc(params);
        if ("2".equals(req.getInformationType())) {
            String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.GET_STOCK_INFO.getUrl();
            JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.GET_STOCK_INFO.getCode(), url, null, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            JSONArray result = apiResult.getJSONArray("data");
            String code = apiResult.getString("result");
            String message = apiResult.getString("message");
            if ("0".equals(code)) {
                throw new BusinessException(message, String.valueOf(code));
            }

            // Add By Liwq On 2021-01-27 Start
            // 总条数
            Integer total = apiResult.getInteger("total");
            req.getPagerInfo().setTotal(total);
            // Add By Liwq On 2021-01-27 End

            List<DgInventoryResp> dgInventoryRespList = result.toJavaList(DgInventoryResp.class);
            List<DgInventoryResp> dgInventoryRespLists = new ArrayList<DgInventoryResp>();
            for (int i = 0; i < dgInventoryRespList.size(); i++) {
                DgInventoryResp dgInventoryResp = dgInventoryRespList.get(i);
                dgInventoryResp.setChannel(req.getChannel());
                dgInventoryResp.setCreateBy(req.getOperationUserId());
                dgInventoryResp.setModifiedBy(req.getOperationUserId());
                dgInventoryResp.setGmtCreate(LocalDateTime.now());
                dgInventoryResp.setGmtModified(LocalDateTime.now());
                dgInventoryRespLists.add(dgInventoryResp);
            }
            if (dgInventoryRespLists.size() > 0) {
                dgInventoryRespMapper.insertOrUpdateBatch(dgInventoryRespLists);
            }
            Map<String, String> change = new HashMap<>();
            change.put("cargonamecode", "typeCode");
            change.put("cargoname", "typeName");
            change.put("formatsizename", "specs");
            change.put("workentrustid", "userNo");
            change.put("workentrustname", "userName");
            change.put("totalqty", "sumAmount");
            change.put("totalweight", "sumWeight");
            change.put("riskcontrolqty", "watchAmount");
            change.put("riskcontrolweight", "watchWeight");
            change.put("portcontrolweight", "portWeight");
            change.put("portcontrolqty", "portAmount");
            change.put("nocontrolqty", "notAmount");
            change.put("nocontrolweight", "notWeight");
            result = BeanUtil.changeJsonArr(result, change);
            List<DgYardCargoDDTO> dgYardCargoDDTOList = result.toJavaList(DgYardCargoDDTO.class);;
            dgYardCargoDTO.setDgYardCargoDList(dgYardCargoDDTOList);
        } else {
            String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.GET_STOCK_INFO.getUrl();
            JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.GET_STOCK_INFO.getCode(), url, null, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            JSONArray result = apiResult.getJSONArray("data");
            String code = apiResult.getString("result");
            String message = apiResult.getString("message");
            if ("0".equals(code)) {
                throw new BusinessException(message, String.valueOf(code));
            }

            // Add By Liwq On 2021-01-27 Start
            // 总条数
            Integer total = apiResult.getInteger("total");
            req.getPagerInfo().setTotal(total);
            // Add By Liwq On 2021-01-27 End

            List<DgInventoryStatic> dgInventoryRespList = result.toJavaList(DgInventoryStatic.class);
            List<DgInventoryStatic> dgInventoryRespLists = new ArrayList<DgInventoryStatic>();
            for (int i = 0; i < dgInventoryRespList.size(); i++) {
                DgInventoryStatic dgInventoryResp = dgInventoryRespList.get(i);
                dgInventoryResp.setChannel(req.getChannel());
                dgInventoryResp.setCreateBy(req.getOperationUserId());
                dgInventoryResp.setModifiedBy(req.getOperationUserId());
                dgInventoryResp.setGmtCreate(LocalDateTime.now());
                dgInventoryResp.setGmtModified(LocalDateTime.now());
                dgInventoryRespLists.add(dgInventoryResp);
            }
            if (dgInventoryRespLists.size() > 0) {
                dgInventoryStaticMapper.insertOrUpdateBatch(dgInventoryRespLists);
            }
            List<DgYardCargoJDTO> dgYardCargoJDTOList = result.toJavaList(DgYardCargoJDTO.class);;
            dgYardCargoDTO.setDgYardCargoJList(dgYardCargoJDTOList);

        }
        return dgYardCargoDTO;
    }

    /**
     * @author songyf
     * @Description 历史业务量信息查询
     * @Date 2020-08-20 10:36
     * @Param DgCargoInYardQueryReq
     * @return DgCargoInYardDTO
     **/
    @Transactional(rollbackFor = Exception.class)
    public List<DgCargoInYardDTO> getCargoInYard(DgCargoInYardQueryReq req) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", ORG_ID);
        params.put("workentrustid", req.getUserNo());
        params.put("workentrustname", req.getUserName());
        params.put("cargonamecode", req.getTypeCode());
        params.put("cargoname", req.getTypeName());
        params.put("querytype", "1");
        params.put("startdate", req.getStartDate());
        params.put("enddate", req.getEndDate());
        params = apiHelper.reqParamsProc(params);
        String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.GET_HISTORY_BUSINESS_VOLUME.getUrl();
        JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.GET_HISTORY_BUSINESS_VOLUME.getCode(), url, null, params,
            HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
        JSONArray result = apiResult.getJSONArray("data");
        String code = apiResult.getString("result");
        String message = apiResult.getString("message");
        if ("0".equals(code)) {
            throw new BusinessException(message, String.valueOf(code));
        }
        List<DgInventoryHistoryResp> dgInventoryHistoryRespList = result.toJavaList(DgInventoryHistoryResp.class);
        List<DgInventoryHistoryResp> dgInventoryHistoryRespLists = new ArrayList<DgInventoryHistoryResp>();
        for (int i = 0; i < dgInventoryHistoryRespList.size(); i++) {
            DgInventoryHistoryResp dgInventoryHistoryResp = dgInventoryHistoryRespList.get(i);
            dgInventoryHistoryResp.setChannel(req.getChannel());
            dgInventoryHistoryResp.setCreateBy(req.getOperationUserId());
            dgInventoryHistoryResp.setModifiedBy(req.getOperationUserId());
            dgInventoryHistoryResp.setGmtCreate(LocalDateTime.now());
            dgInventoryHistoryResp.setGmtModified(LocalDateTime.now());
            dgInventoryHistoryRespLists.add(dgInventoryHistoryResp);
        }

        dgCargoInYardModel.saveBatch(dgInventoryHistoryRespLists);
        Map<String, String> change = new HashMap<>();
        change.put("cargonamecode", "typeCode");
        change.put("cargoname", "typeName");
        change.put("formatsizename", "specs");
        change.put("workentrustid", "userNo");
        change.put("workentrustname", "userName");
        change.put("cargoinqty", "amount");
        change.put("cargoinweight", "weight");
        result = BeanUtil.changeJsonArr(result, change);
        List<DgCargoInYardDTO> dgCargoInYardDTOList = result.toJavaList(DgCargoInYardDTO.class);;
        return dgCargoInYardDTOList;
    }

    /**
     * @author songyf
     * @Description 质押监管情况查询
     * @Date 2020-08-20 15:00
     * @Param DgCargoControlQueryReq
     * @return DgCargoControlDTO
     **/
    @Transactional(rollbackFor = Exception.class)
    public DgCargoControlDTO getCargoControl(DgCargoControlQueryReq req) {
        Map<String, String> change = new HashMap<>();
        DgCargoControlDTO dgCargoControlDTO = new DgCargoControlDTO();
        List<DgCargoControlJDTO> DgCargoControlJDTO = new ArrayList<>();
        if ("1".equals(req.getQueryType())) {
            Map<String, Object> params = new HashMap<>();
            params.put("id", ORG_ID);
            params.put("workentrustid", req.getUserNo());
            params.put("workentrustname", req.getUserName());
            params.put("querytype", req.getQueryType());
            params.put("cargono", req.getItemNo());
            params = apiHelper.reqParamsProc(params);
            String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.J_CARGOCONTROL.getUrl();
            JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.J_CARGOCONTROL.getCode(), url, null, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            JSONArray result = apiResult.getJSONArray("data");
            String code = apiResult.getString("result");
            String message = apiResult.getString("message");
            if ("0".equals(code)) {
                throw new BusinessException(message, String.valueOf(code));
            }
            List<DgPledgeQueryRespStatic> dgPledgeQueryRespStaticList =
                result.toJavaList(DgPledgeQueryRespStatic.class);
            List<DgPledgeQueryRespStatic> dgPledgeQueryRespStaticLists = new ArrayList<DgPledgeQueryRespStatic>();
            for (int i = 0; i < dgPledgeQueryRespStaticList.size(); i++) {
                DgPledgeQueryRespStatic temp = dgPledgeQueryRespStaticList.get(i);
                temp.setChannel(req.getChannel());
                temp.setCreateBy(req.getOperationUserId());
                temp.setModifiedBy(req.getOperationUserId());
                temp.setGmtCreate(LocalDateTime.now());
                temp.setGmtModified(LocalDateTime.now());
                dgPledgeQueryRespStaticLists.add(temp);
            }
            dgJCargoControlModel.saveBatch(dgPledgeQueryRespStaticLists);
            change.put("shipnamech", "shipName");
            change.put("shipnameen", "engShipName");
            change.put("shipcycleid", "shipNo");
            change.put("cargono", "sellNo");
            change.put("invoyage", "voyage");
            change.put("berthdate", "inDate");
            change.put("cargonamecode", "typeCode");
            change.put("cargoname", "typeName");
            change.put("formatsizename", "specs");
            change.put("cargoshortname", "stampName");
            change.put("stackno", "stampNo");
            change.put("shipcabinqty", "amount");
            change.put("shipcabinweight", "weight");
            change.put("workentrustid", "userNo");
            change.put("workentrustname", "userName");
            change.put("cardno", "billNo");
            change.put("entry_id", "customsNo");
            result = BeanUtil.changeJsonArr(result, change);
            DgCargoControlJDTO = result.toJavaList(DgCargoControlJDTO.class);
            dgCargoControlDTO.setDgCargoControlJDTO(DgCargoControlJDTO);
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("id", ORG_ID);
            params.put("workentrustid", req.getUserNo());
            params.put("workentrustname", req.getUserName());
            params.put("querytype", req.getQueryType());
            params.put("cargonamecode", req.getTypeCode());
            params.put("cargoname", req.getTypeName());
            params = apiHelper.reqParamsProc(params);
            String url = mainBusinessConfig.getDagangUrl() + PortUriEnum.D_CARGOCONTROL.getUrl();
            JSONObject apiResult = apiUtil.sendApiLog(PortUriEnum.D_CARGOCONTROL.getCode(), url, null, params,
                HostConstants.HTTP_METHOD_POST, LOG_NAME, req);
            JSONArray result = apiResult.getJSONArray("data");
            String code = apiResult.getString("result");
            String message = apiResult.getString("message");
            if ("0".equals(code)) {
                throw new BusinessException(message, String.valueOf(code));
            }
            List<DgPledgeQueryRespDynamic> dgPledgeQueryRespDynamic = result.toJavaList(DgPledgeQueryRespDynamic.class);
            List<DgPledgeQueryRespDynamic> dgPledgeQueryRespDynamicLists = new ArrayList<DgPledgeQueryRespDynamic>();
            for (int i = 0; i < dgPledgeQueryRespDynamic.size(); i++) {
                DgPledgeQueryRespDynamic temp = dgPledgeQueryRespDynamic.get(i);
                temp.setChannel(req.getChannel());
                temp.setCreateBy(req.getOperationUserId());
                temp.setModifiedBy(req.getOperationUserId());
                temp.setGmtCreate(LocalDateTime.now());
                temp.setGmtModified(LocalDateTime.now());
                dgPledgeQueryRespDynamicLists.add(temp);
            }
            dgDCargoControlModel.saveBatch(dgPledgeQueryRespDynamicLists);
            change.put("cargonamecode", "typeCode");
            change.put("cargoname", "typeName");
            change.put("formatsizename", "specs");
            change.put("workentrustid", "userNo");
            change.put("workentrustname", "userName");
            change.put("totalqty", "sumAmount");
            change.put("totalweight", "sumWeight");
            change.put("riskcontrolqty", "watchAmount");
            change.put("riskcontrolweight", "watchWeight");
            change.put("portcontrolweight", "portWeight");
            change.put("portcontrolqty", "portAmount");
            result = BeanUtil.changeJsonArr(result, change);
            List<DgCargoControlDDTO> dgCargoControlDDTO = result.toJavaList(DgCargoControlDDTO.class);
            dgCargoControlDTO.setDgCargoControlDDTO(dgCargoControlDDTO);
        }
        return dgCargoControlDTO;
    }

}
